//
//  HMComposePicView.swift
//  CZBKWB31
//
//  Created by Linkon Y on 16/8/17.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
// cell 可重用标示符
private let HMComposePicViewCellId = "HMComposePicViewCellId"

class HMComposePicView: UICollectionView {
    //保存image的数组
    var imageList: [UIImage] = [UIImage]()
    
    //定义闭包 01
    var closure:(() -> ())? 

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 供外界调用的方法
    func addImage(image: UIImage){
        //显示控件
        self.hidden = false
        //增加的数组中去
        imageList.append(image)
        //记住刷新UI
        reloadData()
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        //隐藏当前控件
        self.hidden = true
        //颜色
        backgroundColor = UIColor.clearColor()
        
        //设置代理及注册
        registerClass(HMComposePicViewCell.self, forCellWithReuseIdentifier: "HMComposePicViewCellId")
        dataSource = self
        delegate = self
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        let margin: CGFloat = 5
        let cellWH: CGFloat = (SCREENW - 20 - 2*margin)/3
        //设置size
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        
        //垂直水平间距
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
    }
}

extension HMComposePicView: UICollectionViewDataSource,UICollectionViewDelegate{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let count = imageList.count
        //0 和 9  没有显示+ 号的照片
        //反之显示
        if count == 0 || count == 9  {
            return count
        }
        
        return imageList.count + 1
        
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("HMComposePicViewCellId", forIndexPath: indexPath) as! HMComposePicViewCell
        //除了0 和 9
        if imageList.count == indexPath.item {
            cell.image  = nil
        }else{
            //赋值
            cell.image = imageList[indexPath.item]
            //实例化闭包
            cell.closure = {[weak self] in
                //删除指定图片
                self?.imageList.removeAtIndex(indexPath.item)
                //删除到无照片时  隐藏cell
                if self?.imageList.count == 0 {
                    self?.hidden = true
                }
                //刷新UI
                self?.reloadData()
            }
        }
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        //如果不是0 和 9  张 最后一个加入图片
        if imageList.count == indexPath.item {
            //执行闭包 03
            closure?()
        }
    }
}
//自定义cell
class HMComposePicViewCell: UICollectionViewCell{
    //声明 01
    var closure:(() -> ())?
    //供外界调用
    var image: UIImage?{
        didSet{
            //赋值
            //加号图片
            if image == nil{
                bgimageView.image = UIImage(named: "compose_pic_add")
                bgimageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                //没有图片时隐藏
                deleteBtn.hidden = true
                
            }else{
                bgimageView.image = image
                //解决cell复用问题
                bgimageView.highlightedImage = nil
                //注意此处BUG
                deleteBtn.hidden =  false
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
     // MARK: - 监听事件
    @objc private func btnClick(){
         //执行 03
        closure?()
        
    }
    
    // MARK: - 设置视图
    private func setupUI(){
       
        //增加控件
        contentView.addSubview(bgimageView)
        contentView.addSubview(deleteBtn)
        //增加约束
        bgimageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        deleteBtn.snp_makeConstraints { (make) in
            make.top.trailing.equalTo(contentView)
        }

    }
    //懒加载控件
    private lazy var bgimageView: UIImageView = UIImageView()
    //删除按钮
    private lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        //添加事件
        btn.addTarget(self, action: "btnClick", forControlEvents: UIControlEvents.TouchUpInside)
        btn.setImage(UIImage(named:"compose_photo_close"), forState: UIControlState.Normal)
        return btn
    }()
    
}